//
//  TYHUserHeaderView.m
//  OpenPractice
//
//  Created by tanyuehong on 21/12/18.
//  Copyright © 2018年  lijinghua. All rights reserved.
//

#import <CALayer+YYAdd.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "TYHUserHeaderView.h"
#import "NSString+Calculating.h"
#import "UIButton+AdjustTextAnsImage.h"
#import "UIButton+backgroundColorForState.h"


@interface TYHUserHeaderView ()

@property (nonatomic, weak)UIButton *giftBtn;
@property (nonatomic, weak)UIButton *loginBtn;
@property (nonatomic, weak)UIButton *systemMessage;
@property (strong, nonatomic)UIButton *signInButton;
@property (strong, nonatomic) CALayer *shadowLayer;
@property (strong, nonatomic) UIView *sexIconBg;
@property (strong, nonatomic) UIImageView *sexIcon;
@property (strong, nonatomic) CAGradientLayer *signInLayer;
@property (strong, nonatomic) UIImageView *avatarHeaderView;
@property (strong, nonatomic) UIButton  *userHorView;

@end

@implementation TYHUserHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImage imageNamed:@"User-back-image"];
        [self initAllSubViews];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogin) name:kLoginNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogout) name:kLoginNotification object:nil];
    }
    return self;
}

- (void)dealloc {
   [[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginNotification object:nil];
   [[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginNotification object:nil];
}

- (void)initAllSubViews {
    [self initSettingBtn];
    if ([TYHLoginManager sharedInstance].isLogin) {
        [self initTopBtns];
    } else {
    }
    [self initUerHeaderView];
    [self initMyUserCenterView];
}

- (void)initSettingBtn {
    UIButton *myBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width-40-15, 0, 40, 40)];
    myBtn.imageEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    [myBtn setImage:[UIImage imageNamed:@"user-setting-icon"] forState:UIControlStateNormal];
    [self addSubview:myBtn];
}

- (void)initTopBtns {
    UIButton *giftBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width-90, 20, 40, 40)];
    [giftBtn setImage:[UIImage imageNamed:@"usercenter_gift"] forState:UIControlStateNormal];
    [self addSubview:giftBtn];
    self.giftBtn = giftBtn;
    
    UIButton *sysTemBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width-50, 20, 40, 40)];
    [sysTemBtn setImage:[UIImage imageNamed:@"usercenter_msg"] forState:UIControlStateNormal];
    [sysTemBtn setContentMode:UIViewContentModeScaleToFill];
    [self addSubview:sysTemBtn];
    self.systemMessage = sysTemBtn;
}

- (void)initUerHeaderView {
    UIButton *userHorView = [[UIButton alloc] initWithFrame:CGRectMake(20, 40, 40, 20)];
   // [userHorView setImage:[UIImage imageNamed:@"usercenter_myhonor_bg"] forState:UIControlStateNormal];
    [self addSubview:userHorView];
    self.userHorView = userHorView;
    _avatarHeaderView = [[UIImageView alloc] initWithFrame:CGRectMake(20,25, 60, 60)];
    _avatarHeaderView.backgroundColor = [UIColor clearColor];
    _avatarHeaderView.autoresizingMask = UIViewAutoresizingNone;
    _avatarHeaderView.layer.masksToBounds = YES;
    _avatarHeaderView.layer.cornerRadius = 30;
    [self addSubview:_avatarHeaderView];
    
    UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(85, 25, 80, 30)];
    [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:loginBtn];
    self.loginBtn = loginBtn;
    if ([TYHLoginManager sharedInstance].isLogin) {
        [self userLogin];
    } else {
        [self userLogout];
    }
}

- (void)loginBtnClick:(UIButton *)btn {
    if ([_delegate respondsToSelector:@selector(loginBtnClick:)]) {
        [_delegate loginBtnClick:btn];
    }
}

- (void)initMyUserCenterView {
    UIView *sprateView = [[UIView alloc] initWithFrame:CGRectMake(0, 140, self.width, 5)];
    sprateView.backgroundColor = kOPSeparateBackgroundColor;
    [self addSubview:sprateView];
    
    NSArray *btnArr = @[ @{
                          @"title":@"作业问答",
                          @"mainIcon":@"usercenter_homework",
                          },
                        @{
                          @"title":@"错题本",
                          @"mainIcon":@"usercenter_mistake",
                          },
                         @{
                          @"title":@"我的一课",
                          @"mainIcon":@"usercenter_onlinevideo",
                          },
                         @{
                          @"title":@"我的１对１",
                          @"mainIcon":@"usercenter_fudao",
                          },
                      ];
    
    for (int i = 0; i < btnArr.count; i++) {
        NSDictionary *model = [btnArr objectAtIndex:i];
        NSString *imageStr  = [model objectForKey:@"mainIcon"];
        NSString *text      = [model objectForKey:@"title"];
        
        UIButton *subButton = [self getImageStr:imageStr withText:text withDetailText:nil withFrame:CGRectMake(i*(self.width/btnArr.count), 150, self.width/btnArr.count, 84) withDirectionUpDown:YES withAction:nil];
        [self addSubview:subButton];
    }
}

- (UIButton *)getImageStr:(NSString *)imageStr withText:(NSString *)text withDetailText:(NSString *)detailText withFrame:(CGRect)frame withDirectionUpDown:(BOOL)isUpDown withAction:(void (^)(void))actionBlock{
    UIButton *backButtonView = [UIButton buttonWithType:UIButtonTypeCustom];
    backButtonView.backgroundColor = [UIColor whiteColor];
    [backButtonView setFrame:frame];
    backButtonView.layer.masksToBounds = YES;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView.tag = 100;
    imageView.image = [UIImage imageNamed:imageStr];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    imageView.tag = 200;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:14];
    if (isUpDown && !detailText) {
        titleLabel.font = [UIFont systemFontOfSize:12];
    }
    [titleLabel setTextColor:[UIColor colorWithHex:0x333333]];
    [titleLabel setText:text];
    [titleLabel sizeToFit];
    titleLabel.width += 2;
    
    UILabel *detailLabel = nil;
    if (detailText) {
        detailLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        detailLabel.tag = 300;
        detailLabel.textAlignment = NSTextAlignmentCenter;
        detailLabel.backgroundColor = [UIColor clearColor];
        detailLabel.font = [UIFont systemFontOfSize:10];
        [detailLabel setTextColor:[UIColor colorWithHex:0x999999]];
        [detailLabel setText:detailText];
        [detailLabel sizeToFit];
        detailLabel.width = backButtonView.width;
    }
    
    if (!isUpDown) {
        imageView.centerY = backButtonView.height *.5f;
        titleLabel.centerY = backButtonView.height*.5f;
        imageView.left = (backButtonView.width-(imageView.width+titleLabel.width+8))*.5f;
        titleLabel.left = imageView.right+8;
    }else{
        if (detailText) {
            imageView.centerX = backButtonView.width *.5f;
            titleLabel.centerX = backButtonView.width*.5f;
            detailLabel.centerX = backButtonView.width*.5f;
            imageView.top = (backButtonView.height-(imageView.height+titleLabel.height+detailLabel.height+7+5))*.5f;
            titleLabel.top = imageView.bottom+5;
            detailLabel.top = titleLabel.bottom+5;
            titleLabel.font = [UIFont systemFontOfSize:14];
        }else{
            imageView.centerX = backButtonView.width *.5f;
            titleLabel.centerX = backButtonView.width*.5f;
            imageView.top = (backButtonView.height-(imageView.height+titleLabel.height+5))*.5f;
            titleLabel.top = imageView.bottom+5;
        }
    }
    
    titleLabel.x = ceilf(titleLabel.x);
    detailLabel.x = ceilf(detailLabel.x);
    titleLabel.y = ceilf(titleLabel.y);
    detailLabel.y = ceilf(detailLabel.y);
    
    [backButtonView addSubview:imageView];
    [backButtonView addSubview:titleLabel];
    [backButtonView addSubview:detailLabel];
    return backButtonView;
}

- (void)refreshSignInStatus:(NSDictionary *)signData {
    if ([[signData objectForKey:@"signinStatus"] boolValue]) {
        NSInteger sigDays = [[signData objectForKey:@"singininDays"] integerValue];
        [self.signInButton setTitle:[NSString stringWithFormat:@"已连签%ld天",sigDays] forState:UIControlStateNormal];
        [self.signInButton setImage:[UIImage imageNamed:@"usercenter_signin_right"] forState:UIControlStateNormal];
        CGFloat buttonWidth = 5+15+5+[self.signInButton.titleLabel.text stringSizeWithFont:self.signInButton.titleLabel.font constrainWidth:CGFLOAT_MAX].width;
        self.signInButton.width = buttonWidth;
        [self.signInButton layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:3];
        [self.signInButton setTitleColor:[UIColor colorWithHex:0x666666] forState:UIControlStateNormal];
        [self.signInButton setBackgroundColor:[UIColor colorWithHex:0xf2f2f2] forState:UIControlStateNormal];
        [self.signInLayer removeFromSuperlayer];
        [self.shadowLayer removeFromSuperlayer];
    }else{
        NSString *signContent = [signData objectForKey:@"signinContent"];
        NSString *signInStr = ((signContent.length>0)?signContent:@"每日签到领金币");
        [self.signInButton setTitle:signInStr forState:UIControlStateNormal];
        [self.signInButton setImage:[UIImage imageNamed:@"usercenter_signin"] forState:UIControlStateNormal];
        CGFloat buttonWidth = 13+15+5+[self.signInButton.titleLabel.text stringSizeWithFont:self.signInButton.titleLabel.font constrainWidth:CGFLOAT_MAX].width;
        self.signInButton.width = buttonWidth;
        [self.signInLayer setWidth:buttonWidth];
        [self.signInLayer setPosition:CGPointMake(self.signInLayer.width*.5f, self.signInLayer.height*.5f)];
        self.shadowLayer.frame = self.signInButton.frame;
        [self.signInButton layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageLeft imageTitlespace:3];
        [self.signInButton setTitleColor:[UIColor colorWithHex:0xffffff] forState:UIControlStateNormal];
        [self.signInButton setBackgroundColor:[UIColor clearColor] forState:UIControlStateNormal];
        if (!self.signInLayer.superlayer) {
            [self.signInButton.layer insertSublayer:self.signInLayer atIndex:0];
        }
        if (!self.shadowLayer.superlayer) {
            [self.layer insertSublayer:self.shadowLayer below:self.signInButton.layer];
        }
    }
}

- (void)userLogin {
    
}

- (void)userLogout {
    [self.avatarHeaderView sd_setImageWithURL:[NSURL URLWithString:@"https://static.redskt.com/assets/img/yonghutouxiangnan.png"]];
    [self.loginBtn setTitle:@"注册/登录" forState:UIControlStateNormal];
}

- (CAGradientLayer *)signInLayer {
    if (!_signInLayer) {
        _signInLayer = [CAGradientLayer layer];
        _signInLayer.bounds = CGRectMake(0, 0, 110, 40);
        _signInLayer.startPoint = CGPointMake(0, 0.5f);
        _signInLayer.endPoint = CGPointMake(1, 0.5f);
        _signInLayer.colors = @[(__bridge id)[UIColor colorWithHex:0xfebc4a].CGColor,(__bridge id)[UIColor colorWithHex:0xfb9538].CGColor].copy;
        _signInLayer.zPosition = -1;
    }
    return _signInLayer;
}

- (CALayer *)shadowLayer {
    if (!_shadowLayer) {
        _shadowLayer = [CALayer layer];
        _shadowLayer.backgroundColor = [UIColor colorWithHex:0xffe0b6].CGColor;
        _shadowLayer.cornerRadius = 20;
        _shadowLayer.shadowColor = [UIColor colorWithHex:0xffe0b6].CGColor;
        _shadowLayer.shadowOffset = CGSizeMake(0, 1.5f);
        _shadowLayer.shadowOpacity = 1.0f;
    }
    return _shadowLayer;
}

- (UIButton *)signInButton {
    if (!_signInButton) {
        _signInButton  = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 30)];
        [self addSubview:_signInButton];
    }
    return _signInButton;
}



@end
